package czk.concrent.stampLock.stampLockPractice;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/2 14:18
 */
public class StampedLockDemo3 {
    public static void main(String[] args) {
        //
        StampedLock stampedLock = new StampedLock();
        // 先获取排他读锁
        new Thread(() -> {
            long l = 0L;
            try {
                l = stampedLock.readLock();
                //
                System.out.println("获取读锁了");
                TimeUnit.SECONDS.sleep(3);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                // 释放锁
                stampedLock.unlock(l);
            }

        }).start();
        // 再获取写锁
        // 此时应该不能直接获取，阻塞
        new Thread(() -> {
            long writeLock = 0L;
            try {
                writeLock = stampedLock.writeLock();
                System.out.println("获取写锁了");
            } finally {
                // 释放锁
                stampedLock.unlock(writeLock);
            }
        }).start();
    }
}
